package com.heatup.apt.management.task;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.heatup.apt.common.dao.AccessDeviceMapper;
import com.heatup.apt.common.dao.SmsLogMapper;
import com.heatup.apt.common.util.CommonPropertiesUtil;
import com.heatup.apt.common.util.SmsUtil;
import com.heatup.apt.management.util.ManageConfigPropertiesUtil;
import com.heatup.apt.model.AccessDevice;
import com.heatup.apt.model.SmsLog;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 门禁超时发送短信通知定时器
 *
 * @author: Blank
 * @create: 2016-11-30-下午 5:23
 */
@Component
@EnableScheduling
public class AccessDeviceOfflineSmsSendTask {

    private static final Logger log = LoggerFactory.getLogger(AccessDeviceOfflineSmsSendTask.class);

    //需要通知的手机号
    private String[] SMS_SEND_PHONE_NUM = CommonPropertiesUtil.getString("sms_send_phone_num").trim().split(",");
    //检查 如果是测试添加短信标识
    private String test = CommonPropertiesUtil.getString("template_appid").equals("wxe4dfc45a9f29fb8b") ? "测试" : "";

    @Resource
    private AccessDeviceMapper accessDeviceMapper;

    @Resource
    private SmsLogMapper smsLogMapper;

    /**
     * 每间隔10分钟 扫描门禁设备是否有设备在线超时 则发短信通知
     */
    @Scheduled(cron = "1 */10 * * * ?")
    public void SmsSend() {

        String TOKEN_UPDATE_FLAG = ManageConfigPropertiesUtil.getString("token_update_flag").trim();

        // 1表示启动需要启动定时器
        if ("1".equals(TOKEN_UPDATE_FLAG)) {
            try {
                long start = System.currentTimeMillis();
                log.info("门禁心跳设备异常检测任务开始----->");
                List<AccessDevice> doorDevices = accessDeviceMapper.queryAllAccessDevice();
                for (AccessDevice doorDevice : doorDevices) {
                    log.info("门禁设备: " + doorDevice.toString());
                    // 最后一次心跳时间 距离现在 超时20分钟 相当于 最后一次心跳时间 小于 现在时间减去20分钟
                    if (doorDevice.getLastUpdateTime() != null && doorDevice.getLastUpdateTime().before(DateUtils.addMinutes(new Date(), -20))) {
                        doorDevice.setStoreName(test + doorDevice.getStoreName());
                        SmsLog smsLog = new SmsLog();
                        smsLog.setSendType(2);
                        smsLog.setSendResult(1);
                        smsLog.setStoreName(doorDevice.getStoreName());
                        EntityWrapper<SmsLog> smsLogEntityWrapper = new EntityWrapper<>();
                        smsLogEntityWrapper.setEntity(smsLog);
                        smsLogEntityWrapper.orderBy("send_time", false);
                        List<SmsLog> smsLogList = smsLogMapper.selectList(smsLogEntityWrapper);

                        //最后短信无记录 ||最后一次心跳时间 大于 最后一次短信时间
                        if (smsLogList != null && smsLogList.size() == 0 || smsLogList != null && smsLogList.size() > 0 && doorDevice.getLastUpdateTime().after(smsLogList.get(0).getSendTime())) {
                            log.info("门禁最后心跳时间: " + doorDevice.getLastUpdateTime());
                            if (smsLogList.size() > 0 && smsLog.getSendTime() != null) {
                                log.info(" 短信发送时间: " + smsLog.getSendTime());
                            }

                            for (String mobile : SMS_SEND_PHONE_NUM) {
                                boolean sendResult = SmsUtil.sendAccessDeviceErrorSms(mobile, doorDevice.getStoreName());
                                //发送记录
                                SmsLog smsLogRec = new SmsLog();
                                smsLogRec.setMobile(mobile);
                                smsLogRec.setStoreName(doorDevice.getStoreName());
                                smsLogRec.setUserId(-1);
                                smsLogRec.setSendTime(new Date());
                                smsLogRec.setSendResult(sendResult ? 1 : 2);
                                smsLogRec.setSendType(2);
                                smsLogMapper.insertSelective(smsLogRec);
                                log.info("发送门禁心跳异常通知短信 -->" + smsLogRec.toString());
                            }
                        }
                    }
                }
                long end = System.currentTimeMillis();
                log.info("门禁心跳设备异常检测任务结束-----<< 总计耗时" + (end - start) / DateUtils.MILLIS_PER_SECOND + "秒");

            } catch (Exception ex) {
                ex.printStackTrace();
                log.error("==>>检测门禁设备任务异常：" + ex.toString());
            }
        }

    }

}
